<template>
  <a-drawer
    title="节点配置"
    :maskClosable="true"
    :mask="true"
    width=750px
    placement="left"
    :closable="true"
    @close="onClose"
    :visible="NodeConfigVisiable">
    <a-form :form="form">
      <a-col>
        <a-form-item label='节点编码' v-bind="formItemLayout">
          <a-input disabled v-decorator="['nodeId',{rules: [{ required: true, message: '节点编码不能为空'}]}]"/>
        </a-form-item>
      </a-col>
       <a-col>
        <a-form-item label='节点名称'
                   v-bind="formItemLayout">
          <a-input disabled
                 v-decorator="['name']"/>
        </a-form-item>
      </a-col>
      <a-col>
        <a-form-item label='节点类型' v-bind="formItemLayout">
          <a-radio-group disabled
           v-decorator="['nodeType',{rules: [{ required: true, message: '请选择节点类型' }]}]">
            <a-radio value="0">起始节点</a-radio>
            <a-radio value="1">流转节点</a-radio>
          </a-radio-group>
        </a-form-item>
      </a-col>
      <a-col>
        <a-form-item label='表单标题' v-bind="formItemLayout">
          <a-input
            v-decorator="['formTitle',{rules: [{ required: true, message: '表单标题不能为空'}]}]"/>
        </a-form-item>
      </a-col>
      <a-col>
        <a-form-item label='表单类型' v-bind="formItemLayout">
          <a-radio-group @change='formTypeChange'
          v-decorator="['formType',{rules: [{ required: true, message: '表单类型不能为空'}]}]">
            <a-radio value="0">系统表单</a-radio>
<!--            自定义表单暂未实现-->
            <a-radio value="1" disabled>自定义表单</a-radio>
          </a-radio-group>
        </a-form-item>
      </a-col>
    <a-row v-if="ConfigData.formType=='1'">
      <a-col :md="{ span: 12, offset: 3 }" >
          <a-form-item  label='表单路径' v-bind="formItemLayout">
            <a-input
              v-decorator="['formPath',{rules: [{ required: true, message: '表单路径不能为空'}]}]"/>
          </a-form-item>
      </a-col>
      <a-col :span="6">
            <a-button
               style="float:right;">
               预览表单</a-button>
      </a-col>
    </a-row>
    <a-row v-if="ConfigData.formType=='0'">
      <a-col :span="12" :offset="3">
          <a-form-item  label='关联表单' v-bind="formItemLayout">
            <a-select
              show-search
              :filter-option="filterOption"
              v-decorator="['formId',{rules: [{ required: true, message: '请选择表单' }]}]">
              <a-select-option v-for="r in formData" :key="r.formId">{{r.formName}}</a-select-option>
            </a-select>
          </a-form-item>
      </a-col>
      <a-col :span="6" style="margin-top: 10px">
        <a @click="viewForm()">预览</a>
        <a @click="editForm()">编辑</a>
        <a @click="addForm()">创建</a>
      </a-col>
    </a-row>
      <a-col>
        <a-form-item label='分配到角色' v-bind="formItemLayout">
          <a-select
            mode="multiple"
            :allowClear="true"
            style="width: 100%"
            v-decorator="['roleNames']"
            :disabled="candidateVisible">
            <a-select-option v-for="r in roleData" :key="r.roleName">{{r.roleName}}</a-select-option>
          </a-select>
        </a-form-item>
      </a-col>
      <a-col>
          <a-form-item label='分配到用户' v-bind="formItemLayout">
            <a-select
              mode="multiple"
              :allowClear="true"
              style="width: 100%"
              v-decorator="['userIds']"
              :disabled="candidateVisible">
              <a-select-option v-for="r in userData" :key="r.username">{{r.username}}</a-select-option>
            </a-select>
          </a-form-item>
     </a-col>
     <!-- 起始节点时选择图标 -->
      <a-col v-if="ConfigData.nodeType=='0'">
          <a-form-item label='显示图标'
                   v-bind="formItemLayout">
              <a-input ref="icons" v-model="ConfigData.formIcon" placeholder="点击右侧按钮选择图标">
                <a-icon v-if="ConfigData.formIcon" slot="suffix" type="close-circle" @click="deleteIcons"/>
                <a-icon slot="addonAfter" type="setting" style="cursor: pointer" @click="chooseIcons"/>
              </a-input>
          </a-form-item>
      </a-col>
      <a-col v-if="ConfigData.nodeType=='1'">
        <a-form-item label='由前驱节点分配经办用户' v-bind="formItemLayout">
          <a-switch v-model="ConfigData.setCandidateUserPrevious" @change="scCandidateUserPrevious"></a-switch>
        </a-form-item>
        <a-form-item label='优先分配到历史经办人' v-bind="formItemLayout">
          <a-switch v-model="ConfigData.setHistUserFirst"></a-switch>
        </a-form-item>
        <a-form-item label='直接分配到流程创建人' v-bind="formItemLayout">
          <a-switch v-model="ConfigData.setAssignToApplicant" @change="scAssignToApplicant"></a-switch>
        </a-form-item>
      </a-col>
    </a-form>
      <div class="drawer-bootom-button">
        <a-popconfirm title="确定放弃编辑？" @confirm="onClose" okText="确定" cancelText="取消">
          <a-button style="margin-right: .8rem">取消</a-button>
        </a-popconfirm>
        <a-button @click="handleSubmit" type="primary" :loading="loading">保存</a-button>
      </div>
     <!-- 流程配置 -->
    <view-form
      ref="ViewForm"
      :ViewFormVisiable="ViewForm.visiable"
      @close="handleViewFormClose">
    </view-form>
    <edit-form
      ref="EditForm"
      :formVisiable="EditForm.visiable"
      @success="handleEditFormSuccess"
      @close="handleEditFormClose">
    </edit-form>
    <add-form
      ref="AddForm"
      :formVisiable="AddForm.visiable"
      @success="handleAddFormSuccess"
      @close="handleAddFormClose">
    </add-form>
    <!-- 图标选择 -->
    <icons
      @choose="handleIconChoose"
      @close="handleIconCancel"
      :iconChooseVisible="iconChooseVisible">
    </icons>
    <!-- <a-modal :footer="null" :visible="$store.state.setting.modalFlag">
      <router-view/>
    </a-modal> -->
  </a-drawer>
</template>
<script>
import ViewForm from '../form/ViewForm'
import EditForm from '../form/EditForm'
import AddForm from '../form/AddForm'
import Icons from '../menu/Icons'
const formItemLayout = {
  labelCol: { span: 6 },
  wrapperCol: { span: 16 }
}
export default {
  name: 'NodeConfig',
  components: {ViewForm, EditForm, AddForm, Icons},
  props: {
    NodeConfigVisiable: {
      default: false
    }
  },
  data () {
    return {
      // 默认值
      ConfigData: {
        formIcon: '',
        formType: '0',
        nodeType: '0',
        setCandidateUserPrevious: false,
        setHistUserFirst: false,
        setAssignToApplicant: false
      },
      loading: false,
      formItemLayout,
      roleData: [],
      userData: [],
      formData: [],
      form: this.$form.createForm(this),
      ViewForm: {
        visiable: false
      },
      EditForm: {
        visiable: false
      },
      AddForm: {
        visiable: false
      },
      iconChooseVisible: false,
      candidateVisible: false,
      visible: false,
      confirmLoading: false
    }
  },
  methods: {
    scCandidateUserPrevious () {
      if (this.ConfigData.setCandidateUserPrevious === true) {
        let checkVals = this.form.getFieldsValue(['roleNames', 'userIds'])
        if ((checkVals.roleNames === undefined || checkVals.roleNames.length === 0) &&
          (checkVals.userIds === undefined || checkVals.userIds.length === 0)) {
          this.$message.error('开启前请选择关联角色或关联用户')
          this.ConfigData.setCandidateUserPrevious = false
        }
      }
    },
    scAssignToApplicant () {
      if (this.ConfigData.setAssignToApplicant === true) {
        // this.form.setFieldsValue({'roleNames': null, 'userIds': null})
        this.candidateVisible = true
        this.ConfigData.setCandidateUserPrevious = false
        this.ConfigData.setHistUserFirst = false
      } else {
        this.candidateVisible = false
      }
    },
    goModal () {
      this.visible = true
    },
    handleOk () {
      this.confirmLoading = true
      setTimeout(() => {
        this.visible = false
        this.confirmLoading = false
      }, 2000)
    },
    formTypeChange (e) {
      this.ConfigData.formType = e.target.value
    },
    handleCancel () {
      this.visible = false
    },
    openVueCom () {
      this.$store.state.setting.modalFlag = true
    },
    handleViewFormClose () {
      this.ViewForm.visiable = false
    },
    handleEditFormClose () {
      this.EditForm.visiable = false
    },
    handleEditFormSuccess () {
      this.EditForm.visiable = false
      this.$message.success('修改成功')
    },
    handleAddFormClose () {
      this.AddForm.visiable = false
    },
    handleAddFormSuccess () {
      this.$get('form').then((r) => {
        this.formData = r.data.rows
        this.$message.success('创建成功')
        this.AddForm.visiable = false
      })
    },
    handleIconChoose (value) {
      this.ConfigData.formIcon = value
      this.iconChooseVisible = false
    },
    handleIconCancel () {
      this.iconChooseVisible = false
    },
    chooseIcons () {
      this.iconChooseVisible = true
    },
    deleteIcons () {
      this.ConfigData.formIcon = ''
    },
    viewForm () {
      // 当前选中的表单json
      let formId = this.form.getFieldValue('formId')
      if (formId == null) {
        this.$message.warn('请从左侧先选择表单')
        return
      }
      let data = this.formData.find(value => value.formId === formId)
      this.ViewForm.visiable = true
      this.$refs.ViewForm.setFormValues(data)
    },
    editForm () {
      let formId = this.form.getFieldValue('formId')
      if (formId == null) {
        this.$message.warn('请从左侧先选择表单')
        return
      }
      let data = this.formData.find(value => value.formId === formId)
      this.EditForm.visiable = true
      this.$refs.EditForm.setFormData(data)
    },
    addForm () {
      let record = {}
      record.formJson = '{"list":[],"config":{"labelWidth":100,"labelPosition":"right","size":"small","customClass":"","ui":"element","layout":"horizontal","labelCol":3}}'
      this.AddForm.visiable = true
      this.$refs.AddForm.setFormData(record)
    },
    reset () {
      this.loading = false
      this.form.resetFields()
    },
    onClose () {
      this.reset()
      this.$emit('close')
    },
    handleSubmit () {
      this.form.validateFields((err, values) => {
        if (!err) {
          let values = this.form.getFieldsValue(['nodeId', 'nodeType', 'formId', 'formPath', 'formTitle', 'roleNames', 'userIds'])
          if (typeof values !== 'undefined') {
            Object.keys(values).forEach(_key => { this.ConfigData[_key] = values[_key] })
          }
          this.ConfigData.nodeName = this.form.getFieldValue('name')
          if (this.ConfigData.setAssignToApplicant === false) {
            if ((this.ConfigData.userIds === undefined || this.ConfigData.userIds === '') &&
              (this.ConfigData.roleNames === undefined || this.ConfigData.roleNames === '')) {
              this.$message.error('关联角色与关联用户必选其一')
              return
            }
          }
          if (this.ConfigData.nodeType === '0' && (this.ConfigData.formIcon === '' || this.ConfigData.formIcon === undefined)) {
            this.$message.error('图标未选择')
            return
          }
          this.loading = true
          this.$put('process/design/saveNode', {
            ...this.ConfigData
          }).then((r) => {
            this.reset()
            this.$emit('success')
          }).catch(() => {
            this.loading = false
          })
        }
      })
    },
    setFormValues ({...node}) {
      let fields = ['nodeId', 'nodeType', 'formType', 'formId', 'formPath', 'formTitle']
      Object.keys(node).forEach((key) => {
        if (fields.indexOf(key) !== -1) {
          this.form.getFieldDecorator(key)
          let obj = {}
          obj[key] = node[key]
          this.form.setFieldsValue(obj)
        }
      })
      this.ConfigData = node
      this.form.getFieldDecorator('name')
      this.form.setFieldsValue({'name': this.ConfigData.nodeName})
      if (node.roleNames) {
        this.form.getFieldDecorator('roleNames')
        let roleArr = node.roleNames.split(',')
        this.form.setFieldsValue({'roleNames': roleArr})
      }
      if (node.userIds) {
        this.form.getFieldDecorator('userIds')
        let userArr = node.userIds.split(',')
        this.form.setFieldsValue({'userIds': userArr})
      }
    },
    filterOption (input, option) {
      return (
        option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
      )
    }
  },
  watch: {
    NodeConfigVisiable () {
      if (this.NodeConfigVisiable) {
        this.$get('role/getAll').then((r) => {
          this.roleData = r.data
        })
        this.$get('user').then((r) => {
          this.userData = r.data.rows
        })
        this.$get('form/getAll').then((r) => {
          this.formData = r.data
        })
      }
    }
  }
}
</script>
